﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Web;
using System.Net;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;
using System.Linq;

namespace WebApplication1
{
    public partial class First_Level_Dept : System.Web.UI.Page
    {
        string un = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies["UserPhone"] != null)
            {



                DBS md = new DBS();

             
                this.Repeater1.DataSource = md.Dept_List("1");
                this.Repeater1.DataBind();

            }
            else
            {
                if (Request["code"] == null)
                {
                    string httpUrl =
                          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8579b2dae40753d2&redirect_uri=http://www.cmuam.site/First_Level_Dept.aspx&response_type=code&scope=snsapi_base&state=";
                    Response.Redirect(httpUrl);
                }
                else
                {
                    try
                    {
                        string code = Request["code"];

                        //4.根据企业ID:XX,Secret:XXX,获取token
                        string accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
                        string accessTokenResult = HttpGet(accessTokenUrl, "corpid=wx8579b2dae40753d2&corpsecret=JjVqfS47AEc9Z9UHhDvksIGZ_YPgW6Wjo80jGOTxKX8m8yn4VoHDaxRXJI43dIa5");
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        token mytoken = js.Deserialize<token>(accessTokenResult);
                        string tokenValue = mytoken.access_token;

                        //5.获取UserInfo,包含userId
                        string userinfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
                        string userinfojson = HttpGet(userinfoUrl, "access_token=" + tokenValue + "&code=" + code);
                        userinfo userinfo1 = js.Deserialize<userinfo>(userinfojson);
                        string UserId = userinfo1.UserId;

                        //6.根据userId获取通讯录中用户的详细信息
                        string userinfodetailURL = "https://qyapi.weixin.qq.com/cgi-bin/user/get";
                        string userinfodetailResult = HttpGet(userinfodetailURL, "access_token=" + tokenValue + "&userid=" + UserId);
                        string[] sArray = userinfodetailResult.Split(new string[] { "mobile", "gender" }, StringSplitOptions.RemoveEmptyEntries);
                        string[] sArray2 = userinfodetailResult.Split(new string[] { "name", "department" }, StringSplitOptions.RemoveEmptyEntries);
                        un = sArray2[1];
                        un = un.Replace("\"", "");
                        un = un.Replace(":", "");
                        un = un.Replace(",", "");

                        string str = sArray[1];
                        str = str.Replace("\"", "");
                        str = str.Replace(":", "");
                        str = str.Replace(",", "");
                        //Label1.Text = str;
                        Response.Cookies["UserPhone"].Value = str;
                        Response.Cookies["Cname"].Value = un;
                        //todo:跳转到微信主页
                        // Response.Redirect("www.sohu.com", true);
                        DBS md = new DBS();
                      
                        this.Repeater1.DataSource = md.Dept_List("1");
                        this.Repeater1.DataBind();


                    }
                    catch (Exception ex)
                    {
                        //TODO 处理异常

                    }
                }
            }
        
        }
        public string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        public class userinfo
        {
            public string UserId { get; set; }
            public string DeviceId { get; set; }
        }

        public class token
        {

            public string access_token { get; set; }
            public int expires_in { get; set; }

        }

        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {

        }
    }
}